A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be . Typical operations performed by shell scripts include file manipulation, program execution, and printing text. A script which sets up the environment, runs the program, and does any necessary cleanup or logging, is called a wrapper.
The term is also used more generally to mean the automated mode of running an operating system shell. Different each use a particular name for these functions. All Unix-like systems include at least one POSIX shell, typically either bash or the zsh compatibility mode.
One example would be to create a version of ls, the command to list files, giving it a shorter command name of l, which would be normally saved in a user's bin directory as /home/''username''/bin/l, and a default set of command options pre-supplied.
LC_COLLATE=C ls -FCas "$@"
Here, the first line uses a shebang to indicate which interpreter should execute the rest of the script, and the second line makes a listing with options for file format indicators, columns, all files (none omitted), and a size in blocks. The LC_COLLATE=C sets the default collation order to not fold upper and lower case together, not intermix with normal filenames as a side effect of ignoring punctuation in the names (dotfiles are usually only shown if an option like -a is used), and the "$@" causes any parameters given to l to pass through as parameters to ls, so that all of the normal options and other syntax known to ls can still be used.
The user could then simply use l for the most commonly used short listing.
Beyond simply providing a set of default for a command, scripts provide for running multiple commands automatically upon script invocation. This one, ll, merely clears the terminal of all other text before running a listing command.
clear
ls -al "$@"
As in the prior example, this ls -al invocation lists the files and directories that are in the directory from which the script is being run, or any directories given after ll on the command line, which are automatically substituted in for the "$@". The -la command options here cause "all" directory contents to be shown in "long" format.
echo 'compiling...'
cc -c foo.c
cc -c bar.c
cc -c qux.c
cc -o myprog foo.o bar.o qux.o
echo 'done.'
The script would allow a user to save the file being edited, pause the editor, and then just run ./build to create the updated program, test it, and then return to the editor. Since the 1980s or so, however, scripts of this type have been replaced with utilities like make which are specialized for building programs.
for img in "$@"; do # for each given image...
# use ${img%.jpg} to get $img w/o the .jpg
png=${img%.jpg}.png # filename for successful PNG
tmp=tmp.png # filename before sure it worked
echo "converting '$img'..."
# Use ImageMagick's "convert" to write our new PNG
# image into our $tmp file - which may fail!
if convert "$img" "$tmp" ; then # if it works...
# convert worked (since we're in here)
# (this script assumes "mv" always succeeds)
mv "$tmp" "$png" # rename tmp file to target png
echo "converted $jpg to $png"
else
# convert failed (since we're in here)
# tell the user about it
echo "conversion to $png failed, result in $tmp"
exit 1 # exit, the 1 indicates an error
fi # the end of the "if" test construct
done # the end of the "for" loop
echo 'all conversions successful'
The jpg2png command can then be run on an entire directory full of JPEG images with just /home/''username''/bin/jpg2png *.jpg
The standard Unix tools sed and awk provide extra capabilities for shell programming; Perl can also be embedded in shell scripts as can other scripting languages like Tcl. Perl and Tcl come with graphics toolkits as well.
Formerly-popular shells include:
Bourne shell features some influence from ALGOL, specifically in the choice of flow control: '''if''' ~ '''then''' ~ '''elif''' ~ '''then''' ~ '''else''' ~ '''fi''', '''case''' ~ '''in''' ~ '''esac'''.Unix Shells By Example, pp 7-10,
The C and Tcl shells have flow-control syntax quite similar to that of similarly-named programming languages. (The latter is actually based on the Tcl interpreter and provides the full Tcl language.)
Newer non-Bourne-like shells in common use on Unix-like and UNIX systems include:
(Nushell, xonch, and PowerShell are cross-platform beyond Unix-likes and UNIX: they also work natively on Windows.)
The standard shell of Microsoft Windows is cmd.exe, which has rudimentary scripting capabilities. It is partly compatible with its even simpler predecessor COMMAND.COM.
So called remote shells such as
Although the distinction between scripting languages and general-purpose high-level programming languages is often debated, scripting languages are typically characterized by their interpreted nature, simplified syntax, and primary use in automating tasks, coordinating system operations, and writing "glue code" between components. Even when scripting languages such as Python, Rexx, or JavaScript support compilation to bytecode or use JIT to improve performance, they are still commonly referred to as "scripting languages" due to their historical association with automation, lightweight tooling, and scripting environments rather than standalone application development.
Scripting is a form of programming. While "scripting" may emphasize lightweight, task-oriented automation, the broader term "programming" encompasses both scripting and software development in compiled or structured languages. As such, scripting involves writing code to instruct a computer to perform specific tasks—meeting the fundamental definition of programming.
While files with the ".sh" file extension are usually a shell script of some kind, most shell scripts do not have any filename extension.
Often, writing a shell script is much quicker than writing the equivalent code in other programming languages. The many advantages include easy program or file selection, quick start, and interactive debugging. A shell script can be used to provide a sequencing and decision-making linkage around existing programs, and for moderately sized scripts the absence of a compilation step is an advantage. Interpretive running makes it easy to write debugging code into a script and re-run it to detect and fix bugs. Non-expert users can use scripting to tailor the behavior of programs, and shell scripting provides some limited scope for multiprocessing.
On the other hand, shell scripting is prone to costly errors. Inadvertent typing errors such as rm -rf * / (instead of the intended rm -rf */) are folklore in the Unix community; a single extra space converts the command from one that deletes all subdirectories contained in the current directory, to one which deletes everything from the file system's root directory. Similar problems can transform cp and mv into dangerous weapons, and misuse of the > redirect can delete the contents of a file.
Another significant disadvantage is the slow execution speed and the need to launch a new process for almost every shell command executed. When a script's job can be accomplished by setting up a pipeline in which efficient filter commands perform most of the work, the slowdown is mitigated, but a complex script is typically several orders of magnitude slower than a conventional compiled program that performs an equivalent task.
There are also compatibility problems between different platforms. Larry Wall, creator of Perl, famously wrote that "It's easier to port a shell than a shell script", referring to the inconsistent behavior of command-line programs across systems. (His specific example would have been fixed by POSIX standardization of [[grep]].)
Similarly, more complex scripts can run into the limitations of the shell scripting language itself; the limits make it difficult to write quality code, and extensions by various shells to ameliorate problems with the original shell language can make problems worse.
Many disadvantages of using some script languages are caused by design flaws within the language syntax or implementation, and are not necessarily imposed by the use of a text-based command-line; there are a number of shells which use other shell programming languages or even full-fledged languages like Scsh (which uses Scheme).
For example, Bash supports much of the original Bourne shell syntax and offers a POSIX-compliant mode to improve portability. However, Bash also includes a number of extensions not found in POSIX, commonly referred to as bashisms. While these features enhance scripting capabilities, they may reduce compatibility with other shells like Dash or KornShell.
A script that uses features specific to a certain shell may use a matching shebang (#!) as the first line, so that the operating system will use the specified interpreter (e.g. /bin/bash) to run the script, though this will not be sufficient when a feature is added to a shell without changing its name, or when one manually runs the script (e.g. sh foo.sh).
A script can also check which shell it is being ran on and exit before the missing features are used, for example:
if ; then
die() { printf '%s\n' "$1" >&2; exit 1; }
die "Not bash 4 or above. Need bash 4 or above."
fi
declare -A dictionary
In the example above, the opening lines of the script is written in pure POSIX shell. When a non-bash shell run the script, $BASH_VERSINFO will not be set; this triggers the test and causes the script to exit before the incompatible line is reached. When a bash version prior to 4.x runs the script, the same test is triggered by numeric comparison (-lt). ( declares an associative array, a feature new to bash 4.0 and not found on previous versions.)
Scripting languages are, by definition, able to be extended. On Unix and other POSIX-compliant systems, awk and sed are used to extend the string and numeric processing ability of shell scripts. Tcl, Perl, Rexx, and Python have graphics toolkits and can be used to code functions and procedures for shell scripts which pose a speed bottleneck (C, Fortran, assembly language &c are much faster still) and to add functionality not available in the shell language such as sockets and other connectivity functions, heavy-duty text processing, working with numbers if the calling script does not have those abilities, self-writing and self-modifying code, techniques like recursion, direct memory access, various types of sorting and more, which are difficult or impossible in the main script, and so on. Visual Basic for Applications and VBScript can be used to control and communicate with such things as spreadsheets, databases, scriptable programs of all types, telecommunications software, development tools, graphics tools and other software which can be accessed through the Component Object Model.
|
|